<template>
  <div class="equipment-management">
    <h1 class="page-title">装备管理</h1>
    <div class="action-bar">
      <button class="btn btn-primary" @click="openAddModal">添加装备</button>
      <button class="btn btn-secondary" @click="exportToExcel">导出装备清单</button>
    </div>

    <div class="equipment-grid">
      <div v-if="paginatedList.length === 0" class="empty-data-card">暂无装备信息</div>
      <div v-for="item in paginatedList" :key="item.equipId" class="equipment-card">
        <div class="card-header">
          <h4 class="equipment-name">{{ item.equipName }}</h4>
          <span class="equipment-model">{{ item.model }}</span>
        </div>
        <div class="card-body">
          <div class="info-row"><span class="label">编号:</span> <span class="value">{{ item.equipNumber }}</span></div>
          <div class="info-row"><span class="label">状态:</span> <span :class="['status-badge', `status-${item.status}`]">{{ getStatusName(item.status) }}</span></div>
          <div class="info-row"><span class="label">位置:</span> <span class="value">{{ item.position }}</span></div>
          <div class="info-row"><span class="label">上次维保:</span> <span class="value">{{ item.lastMaintain || '无记录' }}</span></div>
          <div class="info-row"><span class="label">分配给:</span> <span class="value value-assign">{{ item.assignedOfficer || '未分配' }}</span></div>
        </div>
        <div class="card-footer">
          <button class="btn-action btn-assign" @click="openAssignModal(item)">分配</button>
          <button class="btn-action btn-edit" @click="openEditModal(item)">编辑</button>
          <button class="btn-action btn-delete" @click="deleteEquipment(item.equipId)">删除</button>
        </div>
      </div>
    </div>

    <Pagination
      v-if="equipmentList.length > itemsPerPage"
      :current-page="currentPage"
      :total-pages="totalPages"
      @page-changed="handlePageChange"
    />

    <EquipmentFormModal v-if="isFormModalOpen" :is-edit-mode="isEditMode" :initial-data="selectedEquipment" @close="closeFormModal" @save="handleSaveEquipment"/>
    <AssignModal
      v-if="isAssignModalOpen"
      :equipment-name="selectedEquipment?.equipName"
      :police-list="policeList"
      @close="closeAssignModal"
      @assign="assignEquipment"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import EquipmentFormModal from './EquipmentFormModal.vue';
import AssignModal from './AssignModal.vue';
import Pagination from '@/components/Pagination.vue';
import * as XLSX from 'xlsx';
import api from '@/utils/axios';

const API_BASE = 'http://localhost:8080/api/auth';

const policeList = ref<any[]>([]);
const equipmentList = ref<any[]>([]);

const currentPage = ref(1);
const itemsPerPage = ref(8);
const totalPages = computed(() => Math.ceil(equipmentList.value.length / itemsPerPage.value));
const paginatedList = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  return equipmentList.value.slice(start, start + itemsPerPage.value);
});

const isFormModalOpen = ref(false);
const isAssignModalOpen = ref(false);
const isEditMode = ref(false);
const selectedEquipment = ref<any>(null);

const fetchEquipments = async () => {
  try {
    const res = await api.get(`${API_BASE}/equipments`);
    equipmentList.value = res.data.data.map((item: any) => ({
      ...item,
      lastMaintain: item.lastMaintain ? formatDate(item.lastMaintain) : '',
      assignedTo: item.assignedOfficer || ''
    }));
  } catch (error) {
    console.error('获取装备失败:', error);
  }
};

const fetchOfficers = async () => {
  try {
    const res = await api.get(`${API_BASE}/officers`);
    policeList.value = res.data.data;
  } catch (error) {
    console.error('获取警员失败:', error);
  }
};

const handleSaveEquipment = async (data: any) => {
  const payload = {
    equipId: data.equipId,
    equipNumber: data.equipNumber,
    equipName: data.equipName,
    model: data.model,
    status: data.status,
    position: data.position,
    lastMaintain: data.lastMaintain || null
  };

  try {
    if (isEditMode.value) {
      await api.put(`${API_BASE}/updateEquips/${data.equipId}`, payload);
    } else {
      await api.post(`${API_BASE}/addEquip`, payload);
    }
    fetchEquipments();
    closeFormModal();
  } catch (error) {
    console.error('保存失败:', error);
  }
};

const deleteEquipment = async (equipId: number) => {
  if (!confirm('确定删除？')) return;
  try {
    await api.delete(`${API_BASE}/deleteEquip/${equipId}`);
    fetchEquipments();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

const assignEquipment = async ({ officerNumber }: { officerNumber: string }) => {
  try {
    await api.post(`${API_BASE}/assign`, {
      equipId: selectedEquipment.value.equipId,
      officerCode: officerNumber // 👈 改这里
    });
    alert('分配成功');
    closeAssignModal();
    fetchEquipments();
  } catch (error) {
    console.error('❌ 分配失败:', error);
    alert('分配失败');
  }
};



const getStatusName = (status: string) => {
  const map: Record<string, string> = {
    '0': '正常',
    '1': '待维修',
    '2': '已分配',
    '3': '报废'
  };
  return map[status] || status;
};

const formatDate = (d: string) => new Date(d).toISOString().split('T')[0];

const handlePageChange = (page: number) => (currentPage.value = page);
const openAddModal = () => {
  isEditMode.value = false;
  selectedEquipment.value = { equipNumber: '', equipName: '', model: '', status: '', position: '', lastMaintain: '' };
  isFormModalOpen.value = true;
};
const openEditModal = (item: any) => {
  isEditMode.value = true;
  selectedEquipment.value = { ...item };
  isFormModalOpen.value = true;
};
const closeFormModal = () => (isFormModalOpen.value = false);
const openAssignModal = (item: any) => {
  selectedEquipment.value = item;
  isAssignModalOpen.value = true;
};
const closeAssignModal = () => (isAssignModalOpen.value = false);

const exportToExcel = () => {
  const data = equipmentList.value.map(item => ({
    装备编号: item.equipNumber,
    装备名称: item.equipName,
    类型: item.model,
    状态: getStatusName(item.status),
    存放位置: item.position,
    上次维保日期: item.lastMaintain,
    分配给: getAssignedOfficerName(item.assignedTo) || '未分配'
  }));
  const sheet = XLSX.utils.json_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, sheet, '装备清单');
  XLSX.writeFile(wb, '装备清单.xlsx');
};

onMounted(() => {
  fetchEquipments();
  fetchOfficers();
});
</script>

<style scoped>
@import "@/assets/styles/views/admin/EquipmentManagement.css";
</style>
